package myapp.baselibrary.dialog;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * Created by yang2 on 2017/6/19.
 */

 class DialogViewHelper {
    private View mContentView = null;
    private SparseArray<WeakReference<View>> mViews ;
    public DialogViewHelper(Context mContext, int mViewLayoutResId) {
        this();
        this.mContentView = LayoutInflater.from(mContext).inflate(mViewLayoutResId,null);

    }


    public DialogViewHelper(){

      mViews = new SparseArray<>();
    }
    public void setContentView(View contentView){
        this.mContentView  = contentView;
    }

    public void setText(int i, CharSequence charSequence) {

        TextView textView = getView(i);
        if (textView!=null){
            textView.setText(charSequence);
        }
    }

    public  <T extends View>T getView(int i) {
        WeakReference<View> viewWeakReference = mViews.get(i);
        View view = null;
        if (viewWeakReference!=null){

            view  = viewWeakReference.get();
            if (view==null){
                view = mContentView.findViewById(i);
                if (view!=null)
                    mViews.put(i,new WeakReference<View>(view));
            }
        }
        return (T) view;
    }

    public void setOnclickListener(int i, View.OnClickListener onClickListener) {
        View viewById = getView(i);
        if (viewById!=null){
            viewById.setOnClickListener(onClickListener);
        }
    }

    public View getContentView() {
        return mContentView;
    }
}
